//
//  TRProductDetailHeaderView.m
//  WeiMiLan
//
//  Created by anan on 14/11/20.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRProductDetailHeaderView.h"

@interface TRProductDetailHeaderView ()
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topScrollViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topViewConstraint;

@property (weak, nonatomic) IBOutlet UILabel *commentCountLabel;



@end

@implementation TRProductDetailHeaderView

- (void)awakeFromNib {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(commentChanged:) name:@"kCommetnCountChanged" object:nil];
}

- (void)commentChanged:(NSNotification *)noti {
    self.commentCountLabel.text = [NSString stringWithFormat:@"最新评论(共有%@条评论)",noti.userInfo[@"count"]];
}
- (void)setInfo:(NSDictionary *)info andImgs:(NSArray *)imgs businnessTag:(NSDictionary*)businnessTag
{
    
    _info = info;
    self.textViewProduct.text = [info ql_stringForKey:@"DESCRIPTION"];
    
    NSLog(@"Text====");
    float fPadding = 16.0; // 8.0px x 2
    CGSize constraint = CGSizeMake(self.textViewProduct.contentSize.width - fPadding, CGFLOAT_MAX);
    
    CGSize size = [self.textViewProduct.text sizeWithFont: self.textViewProduct.font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    
    float fHeight = size.height + 22.0;
    
    
    self.textViewProduct.height = (NSInteger)fHeight;
    
 //   CGRect r = self.textViewProduct.frame;
  //  r.size.width = 304;
  //  self.textViewProduct.frame = r;
   // [self.textViewProduct sizeToFit];

    //修正简介文字位置
 //  CGRect r = self.textViewProduct.frame;
//  self.textViewProduct.frame = r;
   
  
    
    //价格
    NSString *strMark=@"私募：all";
    if ([NSString isBlankString:businnessTag[@"ID"]]) {
        strMark=@"私募:all";
    }else{
        strMark=[NSString stringWithFormat:@"私募:%@",businnessTag[@"ID"]];
    }
  //  NSString *strPrice = [info ql_stringForKey:@"PRICE"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *createDate = [formatter dateFromString:[self.info ql_stringForKey:@"CREATE_DATE"]];
    NSString *str = [NSString stringWithFormat:@"%@",[createDate ql_ToString]];
    str = [str substringFromIndex:5];
    str = [str substringWithRange:NSMakeRange(0, str.length - 3)];
    
    self.labelDesc.text = [NSString stringWithFormat:@"%@ %@",str,strMark];
//    NSInteger statr = [self.labelDesc.text rangeOfString:@"价格:"].location+3;
//    
//    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.labelDesc.attributedText];
//    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(statr, strPrice.length)];
//    [attributedString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:10] range:NSMakeRange(statr, strPrice.length)];
//    [self.labelDesc setAttributedText:attributedString];
    
//    r = self.labelDesc.frame;
//    r.origin.y = self.textViewProduct.frame.origin.y+self.textViewProduct.frame.size.height;
//    self.labelDesc.frame = r;
    
    //图片群
    int y = 0;
 //   NSLog(@"%d",imgs.count);
    if (imgs&&imgs.count>0) {
        for (int i = 0; i<imgs.count; i++) {
            NSDictionary *dic = [imgs objectAtIndex:i];
            int w = [dic ql_intForKey:@"WIDTH"];
            int h = [dic ql_intForKey:@"HEIGHT"];
            int iw = self.scrollView.frame.size.width;
            int ih = iw*h*1.0f/w;
            CGRect r = CGRectMake(0, y, iw, ih);
            y = y + 10 + ih;
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:r];
            UIButton *button = [[UIButton alloc] initWithFrame:r];
            button.tag = i;
            [button addTarget:self action:@selector(buttonShowDetailAction:) forControlEvents:UIControlEventTouchUpInside];
            [imageView sd_setImageWithURL:[NSURL URLWithString:[dic ql_stringForKey:@"PIC_URL"]] placeholderImage:[UIImage imageNamed:@"nodata_public"]];
            [self.scrollView addSubview:imageView];
            [self.imageViews addObject:imageView];
            [self.scrollView addSubview:button];
        }
        
        CGRect sr = self.scrollView.frame;
        sr.origin.y = CGRectGetMaxY(self.textViewProduct.frame) + 10;//+self.labelDesc.frame.size.height;
        sr.size.height = y;
        self.scrollView.frame = sr;
//        r = self.viewTop.frame;
//        r.size.height = sr.origin.y+sr.size.height;
    //    self.viewTop.height = CGRectGetMaxY(self.scrollView.frame);
    }
    

    //

    self.textHeight.constant = 1200;
    
    // 修正viewBottom位置
    
    CGRect r2 = self.frame;
    r2.size.height = CGRectGetMaxY(self.scrollView.frame) + 70;
    //+ 150;//self.viewBottom.frame.size.height+self.viewBottom.frame.origin.y;
    self.frame = r2;
   // self.scrollView.backgroundColor = [UIColor greenColor];
    self.topViewConstraint.constant =  self.topScrollViewHeight.constant = self.scrollView.height + 20;
    [self updateFollowButton];
    _imgs = imgs;
    
    [self setNeedsDisplay];
    
//    if ([QLPublic isAdminAccount]) {
//        self.buttonDownLine.hidden = NO;
//    }else{
//        self.buttonDownLine.hidden = YES;
//    }
    
    
//    for (UIButton *btn in self.buttons) {
//        [btn setImage:[UIImage circleImage:[UIImage imageNamed:@"avator"]] forState:UIControlStateNormal];
//    }
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
  //  NSLog(@"===============%@",NSStringFromCGRect(self.textViewProduct.frame));

//    float fPadding = 16.0; // 8.0px x 2
//    CGSize constraint = CGSizeMake(self.textViewProduct.contentSize.width - fPadding, CGFLOAT_MAX);
//    
//    CGSize size = [self.textViewProduct.text sizeWithFont: self.textViewProduct.font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
//    
//    float fHeight = size.height + 16.0;
    
   
   // self.topContantsView.height = 100;
 
//    CGRect r1 = self.viewBottom.frame;
//    r1.origin.y = CGRectGetMaxY(self.scrollView.frame) + 30;
//    self.viewBottom.frame = r1;
//    
//    CGRect r2 = self.labelCommentCount.frame;
//    r2.origin.y = CGRectGetMaxY(self.scrollView.frame) + 70;
//    self.labelCommentCount.frame = r2;
}

//- (CGFloat)getHeight {
//    return CGRectGetMaxY(self.labelCommentCount.frame);
//}

- (void)updateFollowButton
{
    NSDictionary *ui = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    int uid = [ui ql_intForKey:@"ID"];
    BOOL b = [[QLFollowManager shareInstance]isFollowWithUserId:[self.userInfo ql_intForKey:@"ID"] myUserId:uid];
    if (b==YES) {
        [self.buttonFollow setTitle:@"已关注" forState:UIControlStateNormal];
    }else{
        [self.buttonFollow setTitle:@"关注" forState:UIControlStateNormal];
    }
}

- (void)setImgs:(NSArray *)imgs
{
    _imgs = imgs;
    int i = 0;
    int w = self.scrollView.frame.size.width;
    int h = self.scrollView.frame.size.height;
    if (self.imageViews) {
        for (UIImageView *view in self.imageViews) {
            [view removeFromSuperview];
        }
        [self.imageViews removeAllObjects];
        self.imageViews = nil;
    }
    self.imageViews = [[NSMutableArray alloc] init];
    for (NSDictionary *dic in imgs) {
        CGRect r = CGRectMake(w*i, 0, w, h);
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:r];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.clipsToBounds = YES;
        UIButton *button = [[UIButton alloc] initWithFrame:r];
        button.tag = i;
        [imageView sd_setImageWithURL:[NSURL URLWithString:[dic ql_stringForKey:@"PIC_URL"]] placeholderImage:[UIImage imageNamed:@"nodata_public"]];
        [self.scrollView addSubview:imageView];
        [self.imageViews addObject:imageView];
        [self.scrollView addSubview:button];
        [button addTarget:self action:@selector(buttonShowDetailAction:) forControlEvents:UIControlEventTouchUpInside];
        i++;
    }
    self.scrollView.contentSize = CGSizeMake(w*i, h);
    self.pageControl.numberOfPages = self.imageViews.count;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int size  = self.scrollView.frame.size.width;
    int page = self.scrollView.contentOffset.x/size;
    self.pageControl.currentPage = page;
}

- (void)buttonShowDetailAction:(UIButton*)button
{
    if (self.imgs) {
        int count = (int)self.imgs.count;
        // 1.封装图片数据
        NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
        for (int i = 0; i<count; i++) {
            // 替换为中等尺寸图片
            NSString *url = [self.imgs[i][@"PIC_URL"] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
            MJPhoto *photo = [[MJPhoto alloc] init];
            photo.url = [NSURL URLWithString:url]; // 图片路径
            photo.srcImageView = [self.imageViews objectAtIndex:button.tag]; // 来源于哪个UIImageView
            [photos addObject:photo];
        }
        
        // 2.显示相册
        MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
        browser.userDefaultValue = self.info[@"ID"];
        browser.currentPhotoIndex = button.tag; // 弹出相册时显示的第一张图片是？
        browser.photos = photos; // 设置所有的图片
        //browser.delegate=ApplicationDelegate;
        //browser.userDefaultValue = self.productTypeId;//自定义数据送过去
        [browser show];
    }
}

- (void)setUserInfo:(NSDictionary *)userInfo
{
    _userInfo = userInfo;
    self.labelUserName.text = [self.userInfo ql_stringForKey:@"NAME"];
    self.imageViewIcon.layer.masksToBounds = YES;
    self.imageViewIcon.layer.cornerRadius = 16; //设置图片圆角的尺度
    [self.imageViewIcon sd_setImageWithURL:[NSURL URLWithString:[self.userInfo ql_stringForKey:@"HEAD_PIC_URL"]] placeholderImage:[UIImage imageNamed:@"nodata_userheader"]];
}

- (IBAction)buttonFollowAction:(id)sender
{
    NSDictionary *ui = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    int uid = [ui ql_intForKey:@"ID"];
    BOOL b = [[QLFollowManager shareInstance]isFollowWithUserId:[self.userInfo ql_intForKey:@"ID"] myUserId:uid];
    if (b==YES) {
        [[QLFollowManager shareInstance] deleteFollowWithUserId:[self.userInfo ql_intForKey:@"ID"] myUserId:uid callback:^(BOOL isCache, id data) {
            [SVProgressHUD showSuccessWithStatus:@"关注删除成功"];
            [self updateFollowButton];
        }];
    }else{
        [[QLFollowManager shareInstance] addFollowWithUserId:[self.userInfo ql_intForKey:@"ID"] myUserId:uid callback:^(BOOL isCache, id data) {
            [SVProgressHUD showSuccessWithStatus:@"关注添加成功"];
            [self updateFollowButton];
        }];
    }
}

- (IBAction)buttonConnectSheAction:(id)sender
{
    NSString *message = [NSString stringWithFormat:@"当前咨询的商品是:%@",ApplicationDelegate.shareURL];
    UIAlertView *alert = [[UIAlertView alloc] init];
    [alert setTitle:@"提示"];
    [alert setMessage:message];
    [alert addButtonWithTitle:@"确定"];
    [alert addButtonWithTitle:@"取消"];
    alert.tag=1;
    alert.delegate = self;
//    [alert show];
    
    [self alertView:alert clickedButtonAtIndex:0];
}

- (IBAction)buttonUserDetailAction:(id)sender
{
    [QLPlayerManager openUserHomeWithId:[self.userInfo ql_intForKey:@"ID"] viewController:self.viewController];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==2) {
        if (buttonIndex==1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",self.userInfo[@"PHONE"]]]];//打电话
        }
        return;
    }
}

//- (IBAction)buttonDownloadAction:(id)sender
//{
//    [self.viewController shareToWeixin:nil];
//}

- (IBAction)buttonMakeCallAction:(id)sender
{
    if (self.userInfo) {
        NSString *phoneNum = self.userInfo[@"PHONE"];// 电话号码
        if (phoneNum==nil) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"对不起该用户未绑定手机号码，请先去填写 " delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"是否拨打电话%@",phoneNum] delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
        alert.tag = 2;
        [alert show];
    }
}

//- (IBAction)buttonDownLineAction:(id)sender
//{
//    NSDictionary *ui = [[QLUserManager shareInstance] getLastUserInfoFromNative];
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
//    [dic ql_setObject:[ui ql_stringForKey:@"ID"] forKey:@"userId"];
//    [dic ql_setObject:[self.info ql_stringForKey:@"ID"] forKey:@"ID"];
//    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
//    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//    [requestManager GET:@"http://ping.vsmu.cn/app/Interface/Product?type=2009" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        [SVProgressHUD showSuccessWithStatus:responseObject[@"MESSAGE_INFO"][@"MESSAGE"]];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        [SVProgressHUD showErrorWithStatus:STR_MSG_NETWORK_ERROR];
//    }];
//}

@end
